# -*- coding: utf-8 -*-
"""
http://www.swiftpass.cn/
"""
import hashlib
import json
import random
import string
import urllib
from collections import OrderedDict

import requests
import xmltodict
from dicttoxml import dicttoxml
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)
_GATEWAY = 'https://pay.swiftpass.cn/pay/gateway'
APP_CONF = {
    '102512262653': {
        'API_KEY': '5de99a1021150f133d5cb75fa81e7a0f'
    },
    '102562262743': {
        'API_KEY': '61cd0a8eb1d8c57be3af5e34c75e8cbd'
    },
    '101560269892': {
        'API_KEY': 'c9f41dff675da4694072d375ec3a3db8'
    },  # 接durotar支付宝，文档是扫码的，他们说是扫码破解的wap.
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info['service']
    mch_id = info['app_id']
    api_key = _get_api_key(mch_id)
    parameter_dict = {
        'service': service,
        'version': '2.0',
        'mch_id': mch_id,
        'out_trade_no': pay.id,
        'body': 'charge',
        'total_fee': str(int(pay_amount * 100)),
        'mch_create_ip': _get_device_ip(info),
        'notify_url': '{}/pay/api/{}/swiftpass/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH),
        'nonce_str': pay.id,
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    xml_data = dicttoxml(parameter_dict)
    headers = {'Content-Type': 'application/xml'}
    _LOGGER.info("swiftpass data before charge: %s", xml_data)
    response = requests.post(_GATEWAY, data=xml_data, headers=headers, timeout=3).text
    _LOGGER.info("swiftpass data rsp : %s", response)
    d = xmltodict.parse(response)
    _LOGGER.info("swiftpass data d : %s", d)
    return {
        'charge_info': d[u'xml'][u'code_url'],
    }


def check_notify_sign(request):
    data = xmltodict.parse(request.body)['xml']
    sign = data['sign']
    data.pop('sign')
    mch_id = data.get('mch_id')
    api_key = _get_api_key(mch_id)
    calculated_sign = generate_sign(data, api_key)
    if sign != calculated_sign:
        _LOGGER.info("swiftpass sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % data)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('swiftpass event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay or pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['pay_result'])
    mch_id = pay.mch_id
    trade_no = data['transaction_id']
    total_fee = data['total_fee']
    total_fee = float(total_fee) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 0:
        _LOGGER.info('swiftpass check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def gen_xml(parameter):
    s = '<xml>'
    for k in sorted(parameter.keys()):
        s += '<' + k + '><![CDATA[' + parameter[k] + ']]></' + k + '>'
    s += '</xml>'
    return s


def query_charge(pay_order, app_id):
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('service', 'unified.trade.query'),
        ('mch_id', app_id),
        ('out_trade_no', str(pay_order.id)),
        ('nonce_str', ''.join(random.sample(string.ascii_letters + string.digits, 8))),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    xml_content = gen_xml(parameter_dict)
    response = requests.post(_GATEWAY, data=xml_content, timeout=3)
    _LOGGER.info("swiftpass query data: %s", response.text)
    request_body = str(urllib.unquote(response.text).decode('utf8'))
    data = xmltodict.parse(request_body)
    result = int(data['trade_state'])
    order_id = data['transaction_id']
    total_fee = float(data['total_fee']) / 100.0

    if result == 'SUCCESS':
        trade_no = order_id
        extend = {
            'trade_status': result,
            'trade_no': order_id,
            'total_fee': total_fee
        }
        _LOGGER.info('swiftpass query order success, mch_id:%s pay_id:%s',
                     pay_order.mch_id, pay_order.id)
        res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                       total_fee, trade_no, extend)
        if res:
            # async notify
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('swiftpass query order fail, status_code: %s', result)
